<?php

namespace App\Http\Controllers;

use App\Http\Helpers\StatusResponse;
use App\Models\Blog;
use App\Models\Classify;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Psy\Util\Json;

class BlogController extends Controller
{
    /**
     * 获取所有的博客
     * @api GET /blogs
     * @param Request $request
     * @return JsonResponse
     */
    public function getAll (Request $request) : JsonResponse
    {
        $blogs = Blog::with(['author', 'classify'])->paginate(10);
        return $this->success($blogs);
    }

    /**
     * 获取某个用户的博客
     */
    public function getUsersBlog ($id) : JsonResponse
    {
        $blogs = Blog::with(['author', 'classify'])->where('author_id', $id)->paginate(10);
        return $this->success($blogs);
    }

    /**
     * 获取单个博客的详情
     * 此方法仅能查询未删除的文章
     * @api GET /blogs/{id}
     */
    public function getBlog ($id) : JsonResponse
    {
        $blog = Blog::with(['author', 'classify'])->find($id);
        if ($blog) {
            return $this->success($blog);
        }
        return $this->failWithArr(StatusResponse::NOT_FOUND);
    }

    /**
     * 获取已经被删除的博客
     * @api GET /blogs/deleted
     * @requireLogin
     */
    public function getDeletedBlog () : JsonResponse
    {
        if (!$this->isAdmin()) {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        $blog = Blog::onlyTrashed()->with(['author'])->get();
        return $this->success($blog);
    }

    /**
     * 新建一篇文章，并发布
     * @api POST /blogs
     * @requireLogin
     */
    public function create (Request $request) : JsonResponse
    {
        $userId = Auth::guard('api')->user()->id;
        if (!$userId) {
            return $this->failWithArr(StatusResponse::NOT_FIND_USER);
        }
        // id
        $classifyId = $request->post('classify_id');
        $blog = Blog::query()->create([
            'title' => $request->post('title'),
            'content' => $request->post('content'),
            'author_id' => $userId,
            'classify_id' => $classifyId
        ]);
        if ($classifyId) {
            Classify::query()->find($classifyId)->increment('article_count');
        }
        if ($blog) {
            return $this->success($blog);
        }
        return $this->unknown_err();
    }

    /**
     * 删除文章(软删除，保留文章原始备份)
     * @api DELETE /blogs/soft/{id}
     * @requireLogin
     */
    public function deleteSoft ($id) : JsonResponse
    {
        if (!$blog = Blog::query()->find($id)) {
            return $this->failWithArr(StatusResponse::NOT_FOUND);
        }
        if (!$this->isAdminOrSelf($blog->author_id)) {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        $classifyId = $blog->classify_id;
        if ($classifyId) {
            Classify::query()->find($classifyId)->decrement('article_count');
        }
        if ($blog->delete()) {
            return $this->success();
        }
        return $this->unknown_err();
    }

    /**
     * 还原软删除的文章
     * @api GET /blogs/restore/{id}
     * @requireLogin
     */
    public function restore ($id) : JsonResponse
    {
        if (!$this->isAdmin()) {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        $article = Blog::onlyTrashed()->where('id', $id);
        $classify_id = $article->first()->classify_id;
        $result = $article->restore();
        if ($classify_id) {
            Classify::query()->find($classify_id)->increment('article_count');
        }
        if ($result) {
            return $this->success();
        }
        return $this->unknown_err();
    }



    /**
     * 更新内容操作
     * @api PUT /blogs/{id}
     * @requireLogin
     */
    public function update ($id) : JsonResponse
    {
        if (!$blog = Blog::query()->find($id)) {
            return $this->failWithArr(StatusResponse::NOT_FOUND);
        }
        // 校验用户是否合法
        if (!$this->isAdminOrSelf($blog->author_id)) {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        // 检查分类是否变更
        $classify_id = \request('classify_id');
        if ($blog->classify_id !== $classify_id) {
            if ($blog->classify_id) {
                Classify::query()->find($blog->classify_id)->decrement('article_count');
            }
            if ($classify_id) {
                Classify::query()->find($classify_id)->increment('article_count');
            }
        }
        if ($blog->update([
            'title' => request('title'),
            'content' => request('content'),
            'classify_id' => $classify_id
        ])) {
            return $this->success();
        }
        return $this->unknown_err();
    }

    /**
     * 获取某分类的文章
     * @param $classify_id
     * @return JsonResponse
     */
    public function getClassifyBlog ($classify_id) : JsonResponse
    {
        return $this->success(Blog::query()->with(['author'])->where('classify_id', $classify_id)->get());
    }

    /**
     * 模糊搜索
     * @param $keyword
     * @return JsonResponse
     */
    public function search ($keyword) : JsonResponse
    {
        if ($keyword === ''){
            return $this->failWithArr(StatusResponse::FORM_INCOMPLETE);
        }
        return $this->success(Blog::query()->where('title', 'like', '%'.$keyword.'%')->paginate());
    }
}
